import React from 'react'
import { message } from 'antd'
import { setToken, clearWindow, addWindow, delWindow } from '../redux/actions'
import { $get, $delete, $post, $put } from '@js/authRequest'

export default class Component extends React.Component {
  $get = $get
  $post = $post
  $put = $put
  $delete = $delete
  state = {
    _fileList: [], // 已有文书列表
    _fileListLoaded: false,
    _fileCreating: false,
    _printing: false // 打印中
  }

  // 获取案件文书列表
  $getFileList (caseid) {
    this.setState({
      _fileListLoaded: false
    })
    return new Promise((resolve, reject) => {
      this.$get(`/api/vendor/case/file/${caseid}`, {
        current: 1,
        page_size: 1000
      })
        .then(res => {
          if (res.status === 1) {
            const data = {
              _fileList: res.data.list,
              _fileListLoaded: true
            }
            this.setState(data, () => {
              resolve(data)
            })
          } else {
            reject(new Error(res.message))
          }
        })
    })
  }

  // 生成指定文书
  $createDoc (caseid, fileNames = [], bizid = '', notice = '') {
    const hide = message.loading(notice || '文书生成中', 120)
    this.setState({
      _fileCreating: true
    })
    const data = {
      caseid,
      filename: fileNames
    }
    if (bizid) {
      data.bizid = bizid
    }
    return new Promise((resolve, reject) => {
      this.$post('/api/vendor/case/file', data).then(res => {
        hide()
        this.setState({
          _fileCreating: false
        })
        if (res.status === 1) {
          this.$getFileList(caseid)
            .then(() => resolve(res.data))
        } else {
          throw new Error(res.message)
        }
        return res.data
      }).catch(e => {
        hide()
        this.setState({
          _fileCreating: false
        })
        message.warning(e)
      })
    })
  }

  /**
   * 打开菜单
   */
  $openPage ({ id = '', title = '', componentName = '', closable = true, meta = {}, isHome = false }) {
    this.props.addWindow({ id, title, componentName, closable, meta, isHome })
  }

  // 查看pdf文书
  $readerPdf (filename, id, caseid, readonly = false) {
    this.$openPage({ id: `${filename}-${id}`, title: `${filename}`, componentName: 'PdfReader', meta: { caseid: caseid, fileid: id, readonly } })
  }

  // 查看指定名称的文书
  $readerFileByName (filename, caseid) {
    const list = this.state._fileList
    let id = ''
    for (let i = 0; i < list.length; i++) {
      if (list[i].title.indexOf(filename) !== -1) {
        id = list[i].id
        this.$readerPdf(list[i].title, id, caseid)
        break
      }
    }
    if (!id) {
      message.warning('文书不存在！')
    }
  }

  // 查看文书id的文书
  $readerFileById (fileid, caseid) {
    const list = this.state._fileList || []
    let index = -1
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === fileid) {
        index = i
        this.$readerPdf(list[i].title, fileid, caseid)
        break
      }
    }
    if (index === -1) {
      message.warning('文书不存在！')
    }
  }

  // 打印文档
  $print (filepath) {
    this.setState({
      _printing: true
    })
    const oldIframe = document.getElementById('print')
    if (oldIframe) {
      document.body.removeChild(oldIframe)
    }
    const hide = message.loading('文件加载中，准备打印', 120)
    const iframe = document.createElement('iframe')
    iframe.setAttribute('id', 'print')
    iframe.setAttribute('style', 'width: 0; height: 0; position: absolute; top: -500px; left: -500px;')
    iframe.setAttribute('src', filepath)
    iframe.onload = () => {
      hide()
      this.setState({
        _printing: false
      })
      iframe.contentWindow.print()
    }
    document.body.appendChild(iframe)
  }
}

export function mapStateToProps (fn = () => {}) {
  return function (state) {
    const basic = {
      userInfo: state.basic.userInfo,
      token: state.basic.token
    }
    const newState = fn(state)
    return {
      ...basic,
      ...newState
    }
  }
}

export function mapDispatchToProps (fn = () => {}) {
  return function (dispatch) {
    const basic = {
      setToken: (i) => dispatch(setToken(i)),
      clearWindow: (i) => dispatch(clearWindow(i)),
      addWindow: (i) => dispatch(addWindow(i)),
      delWindow: (i) => dispatch(delWindow(i))
    }
    const newState = fn(dispatch)
    return {
      ...basic,
      ...newState
    }
  }
}
